goog.provide('czk.portlet.Portlet');

goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.json');
goog.require('goog.net.XhrIo');

goog.require('czk.ui.ZKComponent');

/**
 * @extends {czk.ui.ZKComponent}
 * @constructor
 */
czk.portlet.Portlet = function() {
  goog.base(this);
  this.xhrIo = new goog.net.XhrIo();
};
goog.inherits(czk.portlet.Portlet, czk.ui.ZKComponent);

czk.portlet.Portlet.prototype.dtid = null;
czk.portlet.Portlet.prototype.cu = null;
czk.portlet.Portlet.prototype.uu = null;

czk.portlet.Portlet.prototype.children = null;
czk.portlet.Portlet.prototype.xhrIO = null;
czk.portlet.Portlet.prototype.onRender = false;


czk.portlet.Portlet.prototype.initialize = function(name, parameter, portlet) {
  goog.base(this, 'initialize', name, parameter, portlet);
  this.dtid = parameter.dt;
  this.cu = parameter.cu;
  this.uu = parameter.uu;

};

czk.portlet.Portlet.prototype.createInit = function(parameter) {
  this.initialize(parameter[1], parameter[2], this);
  this.children = parameter[3];
  this.decorate(goog.dom.getElement(this.name));
};

czk.portlet.Portlet.prototype.sendXhr =
    function(zkcomponent, action, data) {
      if (this.xhrIo.isActive())
        return;
      this.getHandler().unlisten(this.xhrIo, goog.net.EventType.COMPLETE);
      this.getHandler().listen(this.xhrIo, goog.net.EventType.COMPLETE,
          this.handleZKResponse, false, this);

      var serverParams =
          'dtid=' + this.dtid + '&cmd_0=' + action + '&uuid_0=' +
              zkcomponent.name;
      if (data)
        serverParams += '&data_0=' + data;

      this.xhrIo.send(this.uu, 'POST', serverParams);
    };

czk.portlet.Portlet.prototype.handleZKResponse = function(responseRaw) {
  var xhr = responseRaw.target;
  if (!xhr.isSuccess()) {
    return;
  }
  var response = this.evalJSON(xhr.getResponse());  // xhr; // .getResponseJson();

  goog.base(this, 'handleZKResponse', response);

};

czk.portlet.Portlet.prototype.evalJSON = function (s) {
    return (new Function('return (' + s +')'))(); 
    
};

/** @inheritDoc */
czk.portlet.Portlet.prototype.decorateInternal = function(element) {
  goog.base(this, 'decorateInternal', element);
  goog.array.forEach(this.children, this.addZKChild, this);
  this.children = null;
};

/** @inheritDoc */
czk.portlet.Portlet.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');
  if(this.onRender) {
	  var preItems = [];
	  this.getPreItems(preItems);
	  var data = '{"items":' + goog.json.serialize(preItems)+'}';
	  this.sendXhr(this, 'onRender', data);
  }
};

czk.portlet.Portlet.pi = null;

czk.portlet.Portlet.create = function(parameter) {
  var portlet = new czk.portlet.Portlet();
  portlet.createInit(parameter);
};
